0

Why does my MS visual c++ compiler allow me to copy and assign a vector of a struct that has no copy and assign operators?

struct Reading
{
    int hour;
    double temperature;
    Reading(int h, double temp)
        :hour(h), temperature(temp){}
};

//========================================================

int main()
{
    vector<Reading> readings;

    readings = get_readings(readings);//This is OK!!


    keep_window_open();

}
Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
user2904033
  • 133
  • 1
  • 3
  • 13

4 Answers4

3

Because the default copy constructors and assignment operators simply copy every field in your struct.

See section "When do I need to write a copy constructor?" in http://www.cplusplus.com/articles/y8hv0pDG/

PoByBolek
  • 3,775
  • 3
  • 21
  • 22
2

Structs and classes have default copy constructors and assignment operators.

Default constructors and destructors are also generated.

For constructors they are generated if no other constructor is generated.

Operation of copy ctor and assignment operator is a simple memcpy (shallow copy) which is dangerous in some cases.

egur
  • 7,830
  • 2
  • 27
  • 47
1

There are default copy/assignment constructors generated in most circumstances.

This code demonstrates this (I added some constexpr and a bad operator== for demo purposes):

struct Reading
{
  int hour;
  double temperature;
  constexpr Reading(int h, double temp)
      :hour(h), temperature(temp){}
};

constexpr bool operator==(const Reading& r1, const Reading& r2)
{
  return r1.hour == r2.hour && r1.temperature == r2.temperature;
}

int main()
{
  constexpr Reading r1(42, 4.2);
  constexpr Reading r2 = r1; // compiler will generate a default copy constructor here
  static_assert(r1 == r2, "not equal");
}
rubenvb
  • 74,642
  • 33
  • 187
  • 332
0

From cplusplus.com: Copy constructors, assignment operators, and exception safe assignment

When do I need to write a copy constructor?

First, you should understand that if you do not declare a copy constructor, the compiler gives you one implicitly. The implicit copy constructor does a member-wise copy of the source object.

When do I need to write an assignment operator?

First, you should understand that if you do not declare an assignment operator, the compiler gives you one implicitly. The implicit assignment operator does member-wise assignment of each data member from the source object.

DavidRR
  • 18,291
  • 25
  • 109
  • 191