인프런 커뮤니티 질문&답변
copy constructor 안에서 length constructor 호출을 했는데 워닝이 나오는 이유가 궁금합니다.
작성
·
470
0
안녕하세요.
visual studio 사용하고 있습니다.
24번째 줄에서 Warning이 뜹니다.
C26444 Don't try to declare a local variable with no name (es.84)
copy constructor 안에서 length constructor 호출을 했는데 워닝이 나오는 이유가 궁금합니다.
#pragma once
#include <iostream>
class Resource {
public:
int* m_data = nullptr;
unsigned int m_length = 0;
public:
Resource() {
std::cout << "Resource default constructed\n";
}
Resource(unsigned int length) {
std::cout << "Resource length constructed\n";
this->m_data = new int[length];
this->m_length = length;
}
Resource(const Resource& res) {
std::cout << "Resource copy constructed\n";
// 1. ...
Resource(res.m_length);
//// 2 ...
//this->m_data = new int[res.m_length];
//this->m_length = res.m_length;
for (unsigned i = 0; i < m_length; ++i) {
m_data[i] = res.m_data[i];
}
}
~Resource() {
std::cout << "Resource destroyed\n";
if (m_data != nullptr) {
delete[] m_data;
}
}
Resource& operator = (Resource& res) {
std::cout << "Resource copy assignmnet\n";
if (&res == this) {
return *this;
}
if (this->m_data != nullptr) {
delete[] m_data;
}
m_length = res.m_length;
m_data = new int[m_length];
for (unsigned int i = 0; i < m_length; ++i) {
m_data[i] = res.m_data[i];
}
return *this;
}
void print() {
for (unsigned int i = 0; i < m_length; ++i) {
std::cout << m_data[i] << " ";
}
std::cout << '\n';
}
};답변 1
1
안녕하세요 ~
Resource(res.m_length);
이 곳에서 워닝이 발생하는건데 워닝메세지 그대로입니다. 저 C26444 워닝이 영어로는 Avoid unnamed objects with custom construction and destruction 라고 하네요.
앞에서 배우셨을 <8.13 익명 객체> 강의를 떠올려보시면 Resource(res.m_length); 이건 익명 객체라는 것을 알 수 있으실텐데요! (혹시 낯설게 느껴지신다면 해당 강의를 다시 참고해주세요 :)
익명 객체는 R-value 입니다. 즉, 어디 저장하지 않으면 임시로 잠깐 살아있다가 사라지는 그런 메모리입니다.
int a = 3; 여기서 a 는 L-value 이며 3 은 R-value 입니다. 3 은 어디에 뭐 저장하는게 아니라면 잠깐 쓰이고 버릴 그런 메모리가 되는거죠. 3 에 뭘 저장할 수도 없구요!
Resource(res.m_length); 이건 마치 3; 이렇게만 적은 것과 같다는 것입니다.
이런 R-value 를 어디 L-value 변수에 저장한다거나 활용하지 않고 이렇게 사용만 하고 바로 버려지니 아무 기능을 하지 못하는 그런 코드인거죠..!
뭐 에러가 날 코드는 아니지만 기능을 못하는 코드이니 뺄 것을 권유하는 그런 경고라고 할 수 있겠습니다.





