Search code examples
c++atomicvariadic-functions

Why is a copy constructor being called when passing an atomic into a variadic argument?


I'm trying to pass a std::atomic<unsigned int> into a function with a variadic argument as such:

#include <cstdio>
#include <cstdarg>
#include <atomic>

void info(const char* expression, ...)
{
    std::va_list arg;
    va_start(arg, expression);

    std::vprintf(expression, arg);
    std::printf("\n");
    std::fflush(stdout);

    va_end(arg);
}

int main()
{
    std::atomic<unsigned int> value(10);
    info("Testing: %u", value);

    return 0;
}

As is, I get the compiler error: error: use of deleted function ‘std::atomic::atomic(const std::atomic&)’. However, if I change the info call in main to info("Testing: %u", value.load());, it all works fine.

Why is the copy constructor getting called when I don't specify a load?


Solution

  • Copy Constructors are called in 3 circumstances:

    1. When an object is passed by value
    2. When an object is returned by value
    3. When an object is initialized to the value of an object of the same type.

    If you do not want to call the copy constructor, pass the object by reference (preferably constant) to avoid calling the copy constructor.