简体   繁体   中英

struct copying issue in C/C++ compiled with VS2008

I have the following C/C++ code that I'm compiling with Visual Studio 2008:

struct TEST_STRUCT{
    int nV;
    float v;

    TEST_STRUCT()
    {
        nV = 0;
        v = 0.0;
    }
};

TEST_STRUCT v1;
v1.nV = 100;
v1.v = 2.0;

const TEST_STRUCT v2;               //Making it 'const' to prevent any further changes
(TEST_STRUCT)v2 = v1;

int a = v2.nV;                      //'a' is 0, why???

Why am I getting such a strange result?

You just did something very nasty: you discarded your const qualifier.

const TEST_STRUCT v2 = v1;

or

const TEST_STRUCT v2(v1);

Will give you what you want... Unless you are determined to violate the const qualifier which is very, very bad.

As was pointed out, the object you tried to assign to is a temporary object while the original object remains unchanged. This is one of the reasons that the compiler didn't complain. If you wanted to cast the actual object you'd use some thing like this:

const_cast<TEST_STRUCT&>(v2) = v1;

This still won't nessecarily work because this cast result in undefined behavior when applied to an object which started its life-time as a const object: The object may live in read-only memory or the compiler may replace accesses to its members by their corresponding initial values.

The only way to set members of a const object is during construction. You struct conveniently has two constructors: the default constructor you declared and a copy constructor which the compiler will create for you unless it is declared or one of the subobjects (non-static members or base classes) doesn't have a copy constructor. Thus, you'd just write:

TEST_STRUCT const v2(v1);

or

TEST_STRUCT const v2 = v1;

In this case both calls are semantically equivalent although the latter call theoretically involves two copies. If v1 has a different type the two calls are slightly different with the latter call first converting and then copying. Although the copy is normally elided it would still require a copy constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM